/**
 * Created by suweiming on 2019/7/11.
 */
$(function () {
    var query = {},
        $update = $('.btn-update'),
        $delete = $('.btn-delete'),
        $destroy =$('.btn-destroy'),
        $allow = $('.btn-allow'),
        strHtml = $('#form-template').html();

    var config = {
        query: '/com/query?',//分页查询URL,
        create: '/com/create',//create,
        update: '/com/update',
        'delete': '/com/delete',
        off: '/user/off',
        on: '/user/on',
    };
    var btns =[$update,$delete,$destroy,$allow];
    function getUsers() {
        var dtd = $.Deferred();
        if (users.length) {
            dtd.resolve(users);
        } else {
            $.get(config.user, function (data) {
                if (data.code == 200) {
                    users = data.list;
                    dtd.resolve(data.list)
                } else {
                    data.reject(data.error);
                }
            });
        }
        return dtd.promise();
    }
    function search(obj, isForce) {
        var query_ = {};
        $.extend(query_, query, obj instanceof Object ? obj : {});
        $loading.fadeIn();
        var arg = [];
        if (!isForce) {
            if (isSameQueryStr(query_, query)) { //查询条件和上次一样，取消请求
                return $loading.fadeOut();
            }
        }
        var arg = [];
        query = query_;
        query.timestamp = Date.now();
        Object.keys(query_).map(function (key) {
            arg.push(key + '=' + query_[key])
        });
        $.get(config.query + arg.join('&'), function (res) {
            var _$table = $('.table-responsive .table');
            destroyBtn();
            _$table.$table($.extend(TABLE_SETTING, {
                checkbox: true, // 是否显示复选框
                seqNum: true, // 是否显示序号
                sort: search, //排序回调函数
                destroyBtn: destroyBtn, //禁用按钮
                createBtn: createBtn, // 启用她扭
                toolbar: '.toolbar',
                enableSetting: true,//允许自定义显示列
                search: function (obj) { //搜索框查询函数
                    search(obj)
                },
                fields: [
                    {name: 'id', label: '系统ID',},
                    {name: 'name', label: '小程序名称', enableSearch: true},
                    {
                        name: 'title', label: '备注', filter: function (item) {
                            return item.handle;
                        }
                    },
                    {
                        name: 'time', label: '创建时间', filter: function (item) {
                            return "<a href='javascript:void(0)' data-end='"+item.createAt+"' class='order-time'>"+(moment(item.createAt).format('YYYY-MM-DD HH:mm:ss'))+"</a>";
                        }
                    },
                    {
                        name: 'status', label: '系统状态', filter: function (item) {
                            return item.status;
                        }
                    }
                ],
                data: res.list || [],
            }));
            var page = res.page;
            pageInit(page, query, search);
        });
    }
    $update.unbind('click').on('click', function () {
        var $current = $(this).data('json');
        var $modal = layerAlert({
            title: '修改单位"' + $current.name + '"',
            full: true,
            body: ejs.render(strHtml, $current),
            shown: function () {
                validate($modal);
            },
        });
    });
    $delete.unbind('click').on('click', function () {
        var $current = $(this).data('json');
        if (confirm('确认删除"' + $(this).data('json').name + '"?')) {
            $.post(config['delete'], {id: $current.id}, function (xhr, data) {
                if (xhr.code == 200) {
                    fnSuccess('删除成功!');
                    $('tr[id=' + $current.id + ']').remove();
                    // $(self).closest('tr').remove();
                    setTimeout(function () {
                        destroyBtn();
                    }, 0)
                } else {
                    alert('删除失败：' + xhr.error);
                }
            })
        } else {

        }
    });
    $allow.unbind('click').on('click', function () {
        var $modal = layerAlert({
            title: '确认通过用户',
            full:true,
            body: ejs.render(strHtml, {name: ''}),
            shown: function () {
                validate($modal);
            }
        })
    });
    $destroy.unbind('click').on('click', function () {
        var $current = $(this).data('json');
        if (confirm('确认禁用用户"' + $current.name + '"？')) {
            $.post(config.on, {id: $current.id}, function (xhr, data) {
                if (xhr.code == 200) {
                    search({}, true);
                    alert('操作成功!')
                } else {
                    alert(xhr.error);
                }
            });
        }
    });
    function destroyBtn() {
        btns.forEach(function (item) {
            item.data('json', null);
            disableBtn(item);
        });
    }

    function createBtn(_this) {
        destroyBtn();
        btns.forEach(function (item) {
            var $item = $(_this).data('json');
            item.data('json', $item);
            enableBtn(item);
        });
    }
    search({}, true);
    function validate(modal) {
        $('#registrationForm')
            .formValidation('destroy').formValidation($.extend({}, VALIDATION_SETTING, {
            fields: {
                name: {
                    row: '.col-xs-7',
                    validators: {
                        notEmpty: {
                            message: '小程序名称必填'
                        },
                        stringLength: {
                            min: 3,
                            max: 40,
                            message: '小程序名称长度最少3位，最多40位'
                        },
                    }
                },
                title: {
                    row: '.col-xs-7',
                    validators: {}
                },
                time:{
                    row: '.col-xs-7',
                    validators: {}
                },
                status: {
                    row: '.col-xs-7',
                    validators: {}
                }
            }
        }))
            .off('success.form.fv').on('success.form.fv', function (e) {
            e.preventDefault();
            var form = parseSearch($(e.target).serialize());
            var url = '';
            if (form.id) { // is update?
                url = config.update;
            } else {
                url = config.create;
                delete form.id;
            }
            if (form.name) {
                form.name = form.name.trim();
            }
            $.post(url, form, function (xhr, data) {
                if (xhr.code == 200) {
                    // closeLayer(modal);
                    layer.closeAll();
                    fnSuccess(form.id ? '保存成功' : '创建成功!');
                    search({}, true);
                    //modal && modal.modal('hide');
                } else {
                    alert(xhr.error || xhr.msg);
                }
            });

        });
    }

})